package org.dizem.groupon.action;

import com.opensymphony.xwork2.Preparable;
import org.apache.log4j.Logger;
import org.dizem.groupon.model.domain.ItemEntity;
import org.dizem.groupon.service.ItemService;
import org.dizem.util.Pager;

import java.util.List;

/**
 * User: dizem@126.com
 * Time: 11-6-30 下午3:25
 */
public class ItemAction extends BaseAction implements Preparable {
	private Logger log = Logger.getLogger(ItemAction.class);
	private List<ItemEntity> items;
	private ItemService service;
	private int id;
	private ItemEntity item;
	private String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public ItemEntity getItem() {
		return item;
	}

	public void setItem(ItemEntity item) {
		this.item = item;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}


	public List<ItemEntity> getItems() {
		return items;
	}

	public void setItems(List<ItemEntity> items) {
		this.items = items;
	}

	public ItemService getService() {
		return service;
	}

	public void setService(ItemService service) {
		this.service = service;
	}

	public void prepare() throws Exception {
		items = service.loadAll();
	}

	public String get() throws Exception {
		item = service.getById(id);
		log.info("get: load item" + item.getName());
		if (item != null)
			return SUCCESS;
		else
			return ERROR;
	}

	public String listCurrent() throws Exception {
		if (this.getRecordCount() < 0)
			setRecordCount(service.getCurrentCount());
		if (getPage() == null)
			setPage(1);
		Pager p = new Pager(getPage(), getRecordCount(), getPageSize());
		setPageCount(p.getPageCount());
		setPageUrl("listCurrentItem");
		setPage(p.getPage());
		items = service.loadCurrentList(p.getStartPage(), this.getPageSize());
		message = "current";
		log.info("current: load " + items.size() + "items");
		return SUCCESS;
	}

	public String listPast() throws Exception {
		if (this.getRecordCount() < 0)
			setRecordCount(service.getPastCount());
		if (getPage() == null)
			setPage(1);
		Pager p = new Pager(getPage(), getRecordCount(), getPageSize());
		setPageCount(p.getPageCount());
		setPageUrl("listPastItem");
		setPage(p.getPage());
		items = service.loadPastList(p.getStartPage(), this.getPageSize());
		message = "past";
		log.info("pastList: load " + items.size() + "items");
		return SUCCESS;
	}

	public String edit() throws Exception {
		item = service.getById(id);
		log.info("edit: load item:" + item.getName());
		return SUCCESS;
	}

	public String update() throws Exception {
		service.update(item);
		log.info("update: item:" + item.getName());
		return SUCCESS;
	}

	public String delete() throws Exception {
		item = service.getById(id);
		log.info("delete: item:" + item.getName());
		service.delete(item);
		return SUCCESS;
	}

}
